﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;

public class GradientPanel : Panel
{
    private Color ColorA = Color.LightBlue;
    private Color ColorB = Color.Red;
    private LinearGradientMode GradientFillStyle = LinearGradientMode.ForwardDiagonal;
    private Brush gradientBrush;

    public GradientPanel()
    {
        gradientBrush = new LinearGradientBrush(ClientRectangle, ColorA, ColorB, GradientFillStyle);

        handlerGradientChanged = new EventHandler(GradientChanged);
        ResizeRedraw = true;
        DoubleBuffered = true;     
    }

    public Color colourStart
    {
        get { return ColorA; }
        set
        {
            ColorA = value; RefreshBrush(); }
    }
    public Color colourEnd
    {
        get { return ColorB; }
        set
        {
            ColorB = value; RefreshBrush(); }
    }
    public LinearGradientMode colourGradientStyle
    {
        get { return GradientFillStyle; }
        set { GradientFillStyle = value; Invalidate(); RefreshBrush(); }
    }



    private EventHandler handlerGradientChanged;

    
    private void RefreshBrush()
    {
        //I think this IF block should work with no problems, been a while working with brush
        if (gradientBrush != null)
        {
            gradientBrush.Dispose();
        }

        gradientBrush = new LinearGradientBrush(ClientRectangle, ColorA, ColorB, GradientFillStyle);
        Invalidate();
    }

    protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs e)
    {
        e.Graphics.FillRectangle(gradientBrush, ClientRectangle);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (gradientBrush != null) gradientBrush.Dispose();
        }
        base.Dispose(disposing);
    }

    protected override void OnResize(EventArgs eventargs)
    {
        Invalidate();
        //base.OnResize(eventargs);
    }
    protected override void OnSizeChanged(EventArgs e)
    {
        Invalidate();
        //base.OnSizeChanged(e);
    }
    private void GradientChanged(object sender, EventArgs e)
    {
        if (gradientBrush != null) gradientBrush.Dispose();
        gradientBrush = null;
        gradientBrush = new LinearGradientBrush(ClientRectangle, ColorA, ColorB, GradientFillStyle);
        Invalidate();
    }
}